//
//  AddressBookExampleViewController.m
//  AddressBookExample
//

#import "AddressBookExampleViewController.h"

@implementation AddressBookExampleViewController

- (void)logPerson:(ABRecordRef)person {
	CFStringRef name = ABRecordCopyCompositeName(person);
	ABRecordID recId = ABRecordGetRecordID(person);
	NSLog(@"Person Name: %@ RecordID:%d", name, recId);
}

- (void)logGroup:(ABRecordRef)group {
	CFStringRef name = ABRecordCopyValue(group, kABGroupNameProperty);
	ABRecordID recId = ABRecordGetRecordID(group);
	NSLog(@"Group Name: %@ RecordID: %d", name, recId);
}

- (void)logContactsForGroup:(ABRecordRef)group {
	CFArrayRef membersInGroup = ABGroupCopyArrayOfAllMembers(group);
	for (id person in (NSArray *)membersInGroup) {
		[self logPerson:person];
	}
	
	if (membersInGroup) {
		CFRelease(membersInGroup);
	}
}

- (void)groupExamples {
	ABAddressBookRef addressBook = ABAddressBookCreate();
	CFArrayRef allGroups = ABAddressBookCopyArrayOfAllGroups(addressBook);
	
	// 첫번째 그룹에 속한 연락처 출력
	ABRecordRef firstGroup = [(NSArray *)allGroups objectAtIndex:0];
	[self logContactsForGroup:firstGroup];
	
	// 그룹에 연락처 추가 (레코드 ID에 해당하는 연락처 항목이 있다고 가정함)
	ABRecordID contactRecordID = 1;
	ABRecordRef contact = ABAddressBookGetPersonWithRecordID(addressBook, contactRecordID);
	CFErrorRef error;
	ABGroupAddMember(firstGroup, contact, &error);
	ABAddressBookSave(addressBook, &error);
	
	// 연락처가 제대로 추가됐는지 다시 한번 출력
	[self logContactsForGroup:firstGroup];
	
	// 그룹의 첫번째 연락처 항목을 제거
	CFArrayRef membersInGroup = ABGroupCopyArrayOfAllMembers(firstGroup);
	ABRecordRef contactToRemove = [(NSArray *)allGroups objectAtIndex:0];
	ABGroupRemoveMember(firstGroup, contactToRemove, &error);
	ABAddressBookSave(addressBook, &error);
	
	// 제대로 제거됐는지 다시 한번 출력
	[self logContactsForGroup:firstGroup];
	
	CFRelease(allGroups);
	CFRelease(membersInGroup);
	CFRelease(addressBook);
}

- (void)viewDidLoad {
    [super viewDidLoad];
	
	ABAddressBookRef addressBook = ABAddressBookCreate();
	CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
	CFArrayRef allGroups = ABAddressBookCopyArrayOfAllGroups(addressBook);
	for (id person in (NSArray *)allPeople)
		[self logPerson:person];
	for (id group in (NSArray *)allGroups)
		[self logGroup:group];
	CFRelease(allGroups);
	CFRelease(allPeople);
	CFRelease(addressBook);
}

- (void)dealloc {
    [super dealloc];
}

@end
